package StrWordInvert;

public class StrWordInvert {
    public static void main(String[]args){
        try{
        new StrWordInvert().run(args[0]);
        }catch (Exception e){
            System.err.println("Something went wrong");
        }
    }
    public StrWordInvert(){
        str=null;

    }
    public void run(String string){
        //32 - bytecode of "space"
        str=string.trim().getBytes();
        System.out.println("source string: "+string);
        int i=0;                                             //increment iterator of the string
        int j=str.length-1;                                  //decrement iterator of the string
        System.out.println("source  bytes:");
        for(byte itr:str)System.out.print(itr + " ");
        System.out.print("\n");

        while(i!=j){                        //inverting of string
            if(str[i]==32&&str[j]==32){i++;j--;continue;}
            if(str[i]==32&&str[j]!=32){i++;continue;}
            if(str[i]!=32&&str[j]==32){j++;continue;}
            if(str[i]!=32&&str[j]!=32){swap(i,j);i++;j--;continue;}
        }
        i=0;j=0;                     //inverting of words
        int k=0;
        while(i!=str.length){
            if(str[i]==32){
                j=i-1;
                while(k!=j){
                    swap(k,j);
                    k++;
                    j--;
                }
                k=i+1;
            }
            if(i==str.length-1){
                j=i;
                while(k!=j){
                    swap(k,j);
                    k++;
                    j--;
                }
            }
            i++;
        }
        System.out.println("processed   bytes:");
        for(byte itr:str)System.out.print(itr+" ");
        System.out.println("\n");
        System.out.println("processed strring: "+new String(str).toString());
    }
    private void swap(int i,int j){
        byte buf=str[i];
        str[i]=str[j];
        str[j]=buf;
    }
    byte[]str;                              //data string to process
}

